package org.dromara.comm.service.Impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.dromara.comm.Utils.TokenUtil;
import org.dromara.comm.domain.AsUser;
import org.dromara.comm.mapper.AsUserMapper;
import org.dromara.comm.service.AsUserService;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小程序登录
 * @author: 郭伟明
 * @date: 2024-08-07 11:23
 **/

@Service
public class AsUserServiceImpl extends ServiceImpl<AsUserMapper, AsUser> implements AsUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String TOKEN_PREFIX = "user:token:";

    @Autowired
    private AsUserMapper asUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

//    @Autowired
//    private RedisTemplate redisTemplate;

//    @Override
//    public Map<String, Object> login(AsUser asUser) {
//        Map<String, Object> hashMap = new HashMap<>();
//        List<AsUser> sysUsers = asUserMapper.loadUserByUsername(asUser);
//        System.out.println(sysUsers);
//        if (sysUsers.isEmpty()) {
//            hashMap.put("success","密码不对");
//        } else {
//            if (asUser.getUsername() != null && asUser.getPassword() != null) {
//                //校验
//                if (asUser.getPassword()==null){
//                    throw new RuntimeException("密码不为空");
//                }
//                String token = TokenUtil.sign(asUser.getUsername());
//                //断言token不为空，并以用户名作为key，存入redis（看需求是否要放到redis）
//                assert token != null;
//                redisTemplate.opsForValue().set(asUser.getUsername(), token);
//                AsUser asUsers = BeanUtil.copyProperties(sysUsers.get(0), AsUser.class);
//                asUsers.setToken(token);
//                hashMap.put("convert",asUsers);
//            } else {
//                throw new RuntimeException("请输入用户名称，密码！！");
//            }
//        }
//        return hashMap;
//    }

    @Override
    public void register(SysUser sysUser) {
        if(sysUser.getUserName() == null && sysUser.getPassword()== null) {
           throw new RuntimeException("用户名或密码不能为空");
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, sysUser.getUserName());
        wrapper.eq(SysUser::getPassword, sysUser.getPassword());
        List<SysUser> asUsers = sysUserMapper.selectList(wrapper);
        if (!asUsers.isEmpty()){
            throw new RuntimeException("用户名已存在");
        }
        SysUser user = new SysUser();
        user.setUserName(sysUser.getUserName());
        user.setPassword(BCrypt.hashpw(sysUser.getPassword()));
        sysUserMapper.insert(user);
    }
    @Override
    public Map<String, String> createToken(SysUser sysUser) {
        Map<String, String> response = new HashMap<>();
        if (sysUser.getUserName() == null || sysUser.getPassword() == null){
            response.put("error", "用户名或密码不能为空");
        }

        SysUser asUser = asUserMapper.loadUserByUsername(sysUser);

        if(!BCrypt.checkpw(sysUser.getPassword(), asUser.getPassword())) {
            throw new SecurityException("密码错误");
        }

        // 登录用户
        StpUtil.login(asUser.getUserId());

        // 获取生成的 Token
        String token = StpUtil.getTokenValue();

        // 存储用户信息到 Redis，使用 JSON 或序列化的方式
        String userInfo = convertUserToJson(asUser); // 转换为 JSON 字符串
        redisTemplate.opsForValue().set(TOKEN_PREFIX + token, userInfo);

        // 创建一个 JSON 对象来包装 token
        response.put("token", token);
        return response;
    }

    // Helper 方法，将用户信息转换为 JSON 字符串
    private String convertUserToJson(SysUser sysUser) {
        // 你可以使用 Gson、Jackson 或任何其他 JSON 库
        // 示例：使用 Jackson 转换
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(sysUser);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error converting user to JSON", e);
        }
    }

}
